<?php

/**
 * WeEngine System
 *
 * (c) We7Team 2021 <https://www.w7.cc>
 *
 * This is not a free software
 * Using it under the license terms
 * visited https://www.w7.cc for more details
 */

namespace App\Http\Controllers;

use App\Exceptions\LogicErrorException;
use App\Http\Logic\PayLogic;
use App\Http\Validator\PayRPCValidate;
use Illuminate\Http\Request;
use Itwmw\Validate\Attributes\Validator;

class AlipayController
{
    public function pc()
    {
        $data = [
            'pay_type'     => 'alipay',
            'method'       => 'payForPc',
            'subject'      => '测试支付',
            'out_trade_no' => md5(time() . rand(1000, 9999)),
            'amount'       => 0.01,
            'notify_uri'   => MODULE_URI . '/api/pay/notify',
            'return_url'   => MODULE_URL . '/pay'
        ];

        return PayLogic::create($data);
    }

    public function wap()
    {
        $data = [
            'pay_type'     => 'alipay',
            'method'       => 'payForWap',
            'subject'      => '测试支付',
            'out_trade_no' => md5(time() . rand(1000, 9999)),
            'amount'       => 0.01,
            'notify_uri'   => MODULE_URI . '/api/pay/notify',
            'return_url'   => MODULE_URL . '/pay',
            'quit_url'     => MODULE_URL . '/pay'
        ];

        return PayLogic::create($data);
    }

    #[Validator(validate: PayRPCValidate::class, fields: ['out_trade_no'])]
    public function refund(Request $request)
    {
        $data = get_validate_data($request);

        $out_trade_no = $data->get('out_trade_no');

        $log = PayLogic::refund('alipay', $out_trade_no);

        $params = [
            'pay_type'     => 'alipay',
            'method'       => 'refund',
            'out_trade_no' => $out_trade_no,
            'amount'       => $log->amount
        ];

        $result = json_decode(PayLogic::rpc($params)->getContents(), true);

        if (($result['alipay_trade_refund_response']['code'] ?? 0) == 10000) {
            $log->status = 2;
            $log->save();
            return json_success('退款成功');
        }

        throw new LogicErrorException($result['alipay_trade_refund_response']['sub_msg'] ?? '退款请求失败');
    }
}
